# coding:utf-8

import os
import sys
import copy
import timeit
import threading
import time
import chardet
import math
import cv2 as cv
import numpy
import matplotlib.pyplot as plt

orgimg = cv.imread("0046.png", cv.CV_LOAD_IMAGE_UNCHANGED)
if isinstance(orgimg, numpy.ndarray):
    print orgimg.shape
    print orgimg.dtype
    cv.imshow("org image", orgimg)
    # cv.waitKey(0)

# filterimg = cv.GaussianBlur(orgimg, (3, 3), 1.1)
filterimg = orgimg.copy()
rowsumarr = numpy.zeros(filterimg.shape[0], dtype=numpy.float)
sum = 0.
for j in range(filterimg.shape[0]):
    for i in range(filterimg.shape[1]):
        rowsumarr[j] = rowsumarr[j] + filterimg[j][i]
        sum = sum + filterimg[j][i]

rowsumarr = rowsumarr / filterimg.shape[1]
sum = sum / filterimg.shape[0] / filterimg.shape[1]

rowsumarr = rowsumarr / sum

for i in range(rowsumarr.size):
    if (rowsumarr[i] < 1.2):
        rowsumarr[i] = 0
    else:
        rowsumarr[i] = 1
        print i

filterimg = cv.GaussianBlur(orgimg, (3, 3), 1.1)
kernellist = [3., 2., 1., 0., 1., 2., 3.]
sigma = 1.5
dt = 1 / (sigma * math.sqrt(2.0 * math.pi))
sigma = 2.0 * sigma * sigma
for i in range(len(kernellist)):
    kernellist[i] = dt * math.exp((-1.0 * (kernellist[i] ** 2.0)) / sigma)

outimg = orgimg.copy()
for j in range(filterimg.shape[0]):
    for i in range(filterimg.shape[1]):
        filterimg[j][i] = filterimg[j][i] * rowsumarr[j]
        if (filterimg[j][i] > 0):
            if ((outimg[j][i]) > (sum + filterimg[j][i])):
                outimg[j][i] = outimg[j][i] - filterimg[j][i]
            else:
                cc = sum * kernellist[3]
                for k in [0, 1, 2, 4, 5, 6]:
                    l = j + k - 3
                    if (l >= 0 and l < filterimg.shape[0]):
                        cc = cc + outimg[l][i] * kernellist[k]
                outimg[j][i] = cc

cv.imshow("filter imgage", filterimg)
cv.imshow("output imgage", outimg)
cv.waitKey(1)

plt.title("title")
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.plot(rowsumarr, "-k")  # , linewidth=5)
plt.show()

cv.waitKey(0)
